//
//  NDPersonalInfoView.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/30.
//

import SwiftUI
import Combine

struct NDPersonalInfoView: View, TitledView {
    var navigationTitle: String {
        return title ?? "Basic Information"
    }
    
    let title: String?
    let productId: Int
    let orderNum: String
    
    @StateObject private var viewModel: NDPersonalViewModel
    @State private var activeFieldId: Int?
    @State private var showEnumViewPopup = false
    @State private var showAddressPopup = false
    
    var address: AddressModel? {
        return NDUserDefaults.shared.unarchiveObject(for: NDAddressKey, as: AddressModel.self)
    }
    
    init(title: String?, productId: Int, orderNum: String) {
        self.title = title
        self.productId = productId
        self.orderNum = orderNum
        self._viewModel = StateObject(wrappedValue: NDPersonalViewModel(productId: productId, orderNum: orderNum))
    }
    
    var body: some View {
        let navigationConfig = NavigationConfig(
            title: navigationTitle,
            showSystemBackButton: false
        )
        
        let baseConfig = NDBaseConfig(backgroundImgName: "Information background")
        NDAuthenBaseView(baseConfig: baseConfig, navigationConfig: navigationConfig) {
            VStack(spacing: 0) {
                // 顶部图片
                Image(WJAppEnvironment.shared.currentCountry == .india ? "person_top_icon" : "person_top_icon_id")
                    .scaledToFit()
                    .frame(height: 150)
                    .padding(.bottom, 20)
                
                // 主要内容区域 - 占据剩余空间
                ScrollViewReader { proxy in
                    ScrollView {
                        VStack(spacing: 12) {
                            if let energyifies = viewModel.personalInfoModel?.energyify {
                                ForEach(Array(energyifies.enumerated()), id: \.offset) { index, energyify in
                                    
                                    let binding = viewModel.createEnergyifyBinding(
                                        at: index,
                                        field: .fatheraneity
                                    )
                                    let actionType = CommonActionType(value: energyify.jobfy)
                                    let keboardType = KeboardType(value: energyify.eightia)
                                    
                                    NDCommonActionItem(
                                        title: energyify.pitister ?? "",
                                        textContent: binding,
                                        actionType: actionType,
                                        plactHolder: energyify.uvly ?? "",
                                        keboardType: keboardType,
                                        fieldId: index,
                                        onBeginEditing: { fieldId in
                                            activeFieldId = fieldId
                                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
                                                proxy.scrollTo(fieldId, anchor: .top)
                                            }
                                        },
                                        onEndEditing: {
                                            activeFieldId = nil
                                        },
                                        onClickButton: {
                                            endEditing()
                                            viewModel.commonActionItemIndex = index
                                            if actionType == .button {
                                                showEnumViewPopup = true
                                            } else if actionType == .address {
                                                showAddressPopup = true
                                            }
                                        }
                                    )
                                    .id(index)
                                }
                            }
                        }
                        .padding(.top, 16)
                        .padding(.bottom, 16)
                        .padding(.horizontal, 16)
                    }
                    .frame(maxWidth: .infinity)
                    .background(Color(hex: "#FFFFFF"))
                    .cornerRadius(20)
                    .overlay(
                        RoundedRectangle(cornerRadius: 20)
                            .stroke(Color(hex: "#271F24"), lineWidth: 1)
                    )
                    .padding(.horizontal, 16)
                }
                .padding(.top, -45)
                
                Spacer()
                
                nextStepButton
                    .padding(.top, 10)
                    .padding(.bottom, 20)
                    .background(Color.white.ignoresSafeArea(.all, edges: .bottom))
            }
        }
        .onAppear {
            if viewModel.personalInfoModel == nil {
                viewModel.requestPersonalInfo()
            }
            viewModel.requestAddressData()
            viewModel.startTimeStamp = Int(Date().timeIntervalSince1970)
        }
        .onChange(of: viewModel.isLoading) { isLoading in
            DispatchQueue.main.async {
                if isLoading {
                    NDProgressHUD.show()
                } else {
                    if viewModel.errorMessage == nil {
                        
                        NDProgressHUD.dismiss()
                    }
                }
            }
        }
        .onChange(of: viewModel.errorMessage) { msg in
            NDProgressHUD.showInfo(msg)
        }
        .onChange(of: viewModel.saveSuccess) { success in
            if success {
                NotificationCenter.default.post(name: .followUpCurrentProductNotification,
                                                object: nil,
                                                userInfo: nil)
            }
        }
        .overlay(
            Group {
                // 地址选择器弹窗
                if showAddressPopup {
                    Color.black.opacity(0.3)
                        .edgesIgnoringSafeArea(.all)
                        .onTapGesture {
                            showAddressPopup = false
                        }
                    
                    VStack {
                        Spacer()

                        Group {
                            let maxLevel = WJAppEnvironment.shared.currentCountry == .india ? 2 : 3
                            
                            NDAddressPickerView(
                                data: address?.toDataItems() ?? [],
                                maxLevel: maxLevel,
                                config: NDAddressPickerConfig(),
                                actions: NDAddressPickerActions(
                                    onClickConfirmButton: { path in
                                        print("选择结果: \(path.map { $0.name }.joined(separator: "-"))")
                                        
                                        let address = path.map { $0.name }.joined(separator: "-")
                                        showAddressPopup = false
                                        viewModel.updateEnergyifyField(at: viewModel.commonActionItemIndex,
                                                                       field: .fatheraneity,
                                                                       value: address)
                                    },
                                    onSelectionError: { error in
                                        NDProgressHUD.showInfo(error)
                                    },
                                    onCloseAction: {
                                        showAddressPopup = false
                                    }
                                )
                            )
                            .padding(.horizontal, 5)
                            .background(Color(hex: "#FFFFFF"))
                            .cornerRadius(14)
                            .frame(height: 405)
                        }
                    }
                    .transition(.move(edge: .bottom))
                    .animation(.easeInOut(duration: 0.3), value: showAddressPopup)
                    .ignoresSafeArea()
                }
            }
        )
        .ndCustomPopupOnWindow(isPresented: $showEnumViewPopup,
                               style: .actionSheet) {
            NDPersonalEnumView(
                title: viewModel.title,
                dataSource: viewModel.courseatics,
                onSelectionChanged: { index, item in
                    print("选中了第 \(index) 项: \(item?.interestacle ?? "未知")")
                },
                onConfirmAction: { item in
                    print("确认选择: \(item?.interestacle ?? "未知")")
                    showEnumViewPopup = false
                    if let interestacle = item?.interestacle {
                        viewModel.updateEnergyifyField(at: viewModel.commonActionItemIndex,
                                                       field: .fatheraneity,
                                                       value: interestacle)
                    }
                    
                    if let olig = item?.olig {
                        viewModel.updateEnergyifyField(at: viewModel.commonActionItemIndex,
                                                       field: .olig,
                                                       value: String(olig))
                    }
                }, onCloseAction: {
                    showEnumViewPopup = false
                }
            )
            .padding(.horizontal, 5)
            .background(Color(hex: "#FFFFFF"))
        }
    }
    
    var nextStepButton: some View {
        Button(action: nextStepAction) {
            Text(localizedString("Next step"))
                .frame(maxWidth: .infinity)
                .font(.system(size: 18, weight: .bold))
                .foregroundColor(Color(hex: "#FFFFFF"))
                .padding(.horizontal, 15)
                .padding(.vertical, 10)
                .frame(height: 48)
                .background(Color(hex: "#271F24"))
                .clipShape(Capsule())
                .contentShape(Rectangle())
        }
        .padding(.horizontal, 16)
    }
    
    func nextStepAction() {
        endEditing()
        viewModel.requestSavePersonalInfo()
    }
}

